#include "QsUdpManager.h"

QsUdpManager::QsUdpManager(QObject* parent) : QObject(parent) {}

QsUdp* QsUdpManager::addInstance(const QsUdpInfo& info, const QString& name)
{
    QString key = name.isEmpty() ? QString::number(info.port) : name;
    if (m_instances.contains(key)) {
        return m_instances[key];
    }
    QsUdp* udp = new QsUdp(info, this);
    m_instances[key] = udp;
    return udp;
}

void QsUdpManager::removeInstance(const QString& name)
{
    if (m_instances.contains(name)) {
        delete m_instances.take(name);
    }
}

QsUdp* QsUdpManager::getInstance(const QString& name) const
{
    return m_instances.value(name, nullptr);
}

QsUdp* QsUdpManager::findByPort(quint16 port) const
{
    for (auto udp : m_instances) {
        if (udp->info().port == port) {
            return udp;
        }
    }
    return nullptr;
}

QList<QsUdp*> QsUdpManager::allInstances() const
{
    return m_instances.values();
}

QsUdpManager* QsUdpManager::global()
{
    static QsUdpManager* instance = new QsUdpManager();
    return instance;
}

void QsUdpManager::send(const QString& name, quint16 msgType, const QByteArray& data, quint16 r1, quint16 r2)
{
    QsUdp* udp = global()->getInstance(name);
    if (udp) {
        QMetaObject::invokeMethod(udp, "send", Qt::QueuedConnection,
                                  Q_ARG(quint16, msgType),
                                  Q_ARG(QByteArray, data),
                                  Q_ARG(quint16, r1),
                                  Q_ARG(quint16, r2));
    }
} 